package com.sgcc.lms.openstack.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sgcc.lms.openstack.enumeration.StatusCode;
import com.sgcc.lms.openstack.exception.*;
import com.sgcc.lms.openstack.model.po.Project;
import com.sgcc.lms.openstack.service.KeystoneService;
import com.sgcc.lms.openstack.util.OpenStackClientFactory;
import com.sgcc.lms.openstack.util.RestClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.common.Identifier;
import org.openstack4j.model.identity.v3.Token;
import org.openstack4j.model.identity.v3.User;
import org.openstack4j.openstack.OSFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-07-17 14:17
 * @Description:
 */
@Service
@Slf4j
public class KeystoneServiceImpl implements KeystoneService {

    @Value("${keystone.endpoint}")
    private String endpoint;

    private static final String LINE = "=================================================》{}";

    /**
     * @Author 李孟帅
     * @Description 无范围的有用户密码授权，指定域为default
     * @Date 2020/7/18
     **/
    @Override
    public String token(String username, String password) throws JsonProcessingException {
        OSClient.OSClientV3 client = OSFactory.builderV3()
                .endpoint(endpoint)
                .credentials(username, password, Identifier.byId("default"))
                .authenticate();
        Token token = client.getToken();
        //获取tokenId,作为key
        String tokenId = token.getId();
        //将token缓存起来
//        tokenMap.put(tokenId, token);
        OpenStackClientFactory.putToken(token);
        return tokenId;
    }

    /**
     * @Author 李孟帅
     * @Description 项目范围的用户密码授权，指定域为default
     * @Date 2020/7/18
     **/
    @Override
    public String token(String username, String password, String projectId) throws JsonProcessingException {
        OSClient.OSClientV3 client = OSFactory.builderV3().
                endpoint(endpoint)
                .credentials(username, password, Identifier.byId("default"))
                .scopeToProject(Identifier.byId(projectId))
                .authenticate();
        Token token = client.getToken();
        //获取tokenId,作为key
        String tokenId = token.getId();
        //将token缓存起来
        OpenStackClientFactory.putToken(token);
        return tokenId;
    }

    /**
     * @Author 李孟帅
     * @Description 项目范围的用户密码授权，指定域为default
     * @Date 2020/7/18
     **/
    @Override
    public String tokenScope(String username, String password, String projectName) throws JsonProcessingException {
        OSClient.OSClientV3 client = OSFactory.builderV3().
                endpoint(endpoint)
                .credentials(username, password, Identifier.byId("default"))
                .scopeToProject(Identifier.byName(projectName),Identifier.byId("default"))
                .authenticate();
        Token token = client.getToken();
        //获取tokenId,作为key
        String tokenId = token.getId();
        //将token缓存起来
        OpenStackClientFactory.putToken(token);
        return tokenId;
    }

    /**
     * @Author 李孟帅
     * @Description 获取可用的项目范围
     * @Date 2020/7/18
     **/
    @Override
    public List<Project> authProjects(String tokenId) throws IOException, HttpException {
        //构建get请求
        HttpGet httpGet = new HttpGet(endpoint + "/auth/projects");
        //设置请求头
        httpGet.setHeader("X-Auth-Token", tokenId);
        String result = RestClientUtil.execute(httpGet);
        //解析为map
        Map map = (Map) JSONObject.parse(result);
        //封装为bean
        List<Project> projects = JSONArray.parseArray(map.get("projects").toString(), Project.class);
        return projects;
    }

    /**
     * @Author 李孟帅
     * @Description 列出项目
     * @Date 2020/7/18
     **/
    @Override
    public List<Project> projects(String tokenId) throws IOException, HttpException {
        //构建get请求
        HttpGet httpGet = new HttpGet(endpoint + "/projects");
        //设置请求头
        httpGet.setHeader("X-Auth-Token", tokenId);
        String result = RestClientUtil.execute(httpGet);
        //解析为map
        Map map = (Map) JSONObject.parse(result);
        //封装为bean
        List<Project> projects = JSONArray.parseArray(map.get("projects").toString(), Project.class);
        return projects;
    }

    /**
     * @Author 李孟帅
     * @Description 创建项目
     * @Date 2020/7/20
     **/
    @Override
    public Project createProject(String tokenId, Project project) throws IOException, HttpException {
        //构建post请求
        HttpPost httpPost = new HttpPost(endpoint + "/projects");
        //封装参数
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("project", project);
        String jsonString = JSON.toJSONString(hashMap);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        //设置请求头
        httpPost.setHeader("X-Auth-Token", tokenId);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        //设置请求体
        httpPost.setEntity(entity);
        String result = RestClientUtil.execute(httpPost);
        //解析为map
        Map map = (Map) JSONObject.parse(result);
        //封装为bean
        Project object = JSONObject.parseObject(map.get("project").toString(), Project.class);
        return object;

    }

    /**
     * @Author 李孟帅
     * @Description 获取项目信息
     * @Date 2020/7/20
     **/
    @Override
    public Project getProject(String tokenId, String id) throws IOException, HttpException {
        //构建get请求
        HttpGet httpGet = new HttpGet(endpoint + "/projects/" + id);
        //设置请求头
        httpGet.setHeader("X-Auth-Token", tokenId);
        String result = RestClientUtil.execute(httpGet);
        //解析为map
        Map map = (Map) JSONObject.parse(result);
        //封装为bean
        Project object = JSONObject.parseObject(map.get("project").toString(), Project.class);
        return object;
    }

    /**
     * @Author 李孟帅
     * @Description 更新项目
     * @Date 2020/7/20
     **/
    @Override
    public Project updateProject(String tokenId, Project project) throws IOException, HttpException {
        //构建post请求
        String id = project.getId();
        HttpPatch httpPatch = new HttpPatch(endpoint + "/projects/" + id);
        //封装参数
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("project", project);
        String jsonString = JSON.toJSONString(hashMap);
        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        //设置请求头
        httpPatch.setHeader("X-Auth-Token", tokenId);
        httpPatch.setHeader("Content-Type", "application/json;charset=utf8");
        //设置请求体
        httpPatch.setEntity(entity);
        String result = RestClientUtil.execute(httpPatch);
        //解析为map
        Map map = (Map) JSONObject.parse(result);
        //封装为bean
        Project object = JSONObject.parseObject(map.get("project").toString(), Project.class);
        return object;
    }

    /**
     * @Author 李孟帅
     * @Description 删除项目
     * @Date 2020/7/20
     **/
    @Override
    public String deleteProject(String tokenId, String id) throws IOException, HttpException {
        //构建get请求
        HttpDelete httpDelete = new HttpDelete(endpoint + "/projects/" + id);
        //设置请求头
        httpDelete.setHeader("X-Auth-Token", tokenId);
        String result = RestClientUtil.execute(httpDelete);
        return result;
    }

    /**
     * @Author 李孟帅
     * @Description 列出用户
     * @Date 2020/7/18
     **/
    @Override
    public List<? extends User> users(String tokenId) throws NullTokenException {
        //获取客户端
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        List<? extends User> users = osClient.identity().users().list();
        return users;
    }

    /**
     * @Author 李孟帅
     * @Description 创建用户
     * @Date 2020/7/21
     **/
    @Override
    public User createUser(String tokenId, User user) throws NullTokenException, ForbiddenException {
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        User user1 = null;
        try {
            user1 = osClient.identity().users().create(user);
        } catch (Exception e) {
            throw new ForbiddenException("没有权限访问，" + e.getMessage());
        }
        return user1;
    }

    /**
     * @Author 李孟帅
     * @Description 获取用户信息
     * @Date 2020/7/21
     **/
    @Override
    public User getUser(String tokenId, String id) throws NullTokenException, ForbiddenException {
//        OSClient.OSClientV3 osClient = getOSClient(tokenId);
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        User user = null;
        try {
            user = osClient.identity().users().get(id);
        } catch (Exception e) {
            throw new ForbiddenException("没有权限访问，" + e.getMessage());
        }
        return user;
    }

    /**
    * @Author 李孟帅
    * @Description 更新用户
    * @Date 2020/7/21 
    **/
    @Override
    public User updateUser(String tokenId, User user) throws NullTokenException, ForbiddenException {
//        OSClient.OSClientV3 osClient = getOSClient(tokenId);
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        User update = null;
        try {
            update = osClient.identity().users().update(user);
        } catch (Exception e) {
            throw new ForbiddenException("没有权限访问，" + e.getMessage());
        }
        return update;
    }

    /**
    * @Author 李孟帅
    * @Description 删除用户
    * @Date 2020/7/21 
    **/
    @Override
    public ActionResponse deleteUser(String tokenId, String id) throws NullTokenException, ForbiddenException {
//        OSClient.OSClientV3 osClient = getOSClient(tokenId);
        OSClient.OSClientV3 osClient = OpenStackClientFactory.getOpenStackClient(tokenId);
        ActionResponse delete = null;
        try {
            delete = osClient.identity().users().delete(id);
        } catch (Exception e) {
            throw new ForbiddenException("没有权限访问，" + e.getMessage());
        }
        return delete;
    }




}
